common.js ➔ units   A
last analyzed

Complexity

Conditions 3
Paths 16

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 4
nc 16
nop 1
dl 0
loc 7
rs 10
c 1
b 0
f 1
1
// Copyright © 2017 Tangdongxin
2
3
// Permission is hereby granted, free of charge, to any person obtaining
4
// A copy of this software and associated documentation files (the "Software"),
5
// To deal in the Software without restriction, including without limitation
6
// The rights to use, copy, modify, merge, publish, distribute, sublicense,
7
// And/or sell copies of the Software, and to permit persons to whom the
8
// Software is furnished to do so, subject to the following conditions:
9
// The above copyright notice and this permission notice shall be included
10
// In all copies or substantial portions of the Software.
11
12
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
14
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
18
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20
21
let bgColor; // Background color
0 ignored issues
show
Unused Code introduced by
The variable bgColor seems to be never used. Consider removing it.
Loading history...
22
let intColor; // Integer color
0 ignored issues
show
Unused Code introduced by
The variable intColor seems to be never used. Consider removing it.
Loading history...
23
let strColor; // String color
0 ignored issues
show
Unused Code introduced by
The variable strColor seems to be never used. Consider removing it.
Loading history...
24
let keyColor; // K-v key color
0 ignored issues
show
Unused Code introduced by
The variable keyColor seems to be never used. Consider removing it.
Loading history...
25
let defaultColor; // Default text color
0 ignored issues
show
Unused Code introduced by
The variable defaultColor seems to be never used. Consider removing it.
Loading history...
26
let fontStyle; // Font-family
0 ignored issues
show
Unused Code introduced by
The variable fontStyle seems to be never used. Consider removing it.
Loading history...
27
let fontSize; // Font-size
0 ignored issues
show
Unused Code introduced by
The variable fontSize seems to be never used. Consider removing it.
Loading history...
28
let strictOnly; // Only deal with the application/json response
0 ignored issues
show
Unused Code introduced by
The variable strictOnly seems to be never used. Consider removing it.
Loading history...
29
let hideDetails; // Hide the count and size
30
let dontBeatify; // Hide the [str] or [json]
0 ignored issues
show
Unused Code introduced by
The variable dontBeatify seems to be never used. Consider removing it.
Loading history...
31
let strLength; // String length
0 ignored issues
show
Unused Code introduced by
The variable strLength seems to be never used. Consider removing it.
Loading history...
32
let isRelaxedJsonSupport; // Support relaxed json or not.
0 ignored issues
show
Unused Code introduced by
The variable isRelaxedJsonSupport seems to be never used. Consider removing it.
Loading history...
33
let isDebug; // Debug mode
34
let isJsonThisDocument = false;//
0 ignored issues
show
Unused Code introduced by
The variable isJsonThisDocument seems to be never used. Consider removing it.
Loading history...
35
// ===========================================
36
// DEFAULT VALUES
37
// ===========================================
38
const RAND = 'MIKE';
39
const HOV = `H${RAND}`;
0 ignored issues
show
Unused Code introduced by
The constant HOV seems to be never used. Consider removing it.
Loading history...
40
const DIV = `D${RAND}`;
41
const KEY = `K${RAND}`;
42
const STR = `S${RAND}`;
43
const BOOL = `B${RAND}`;
44
const ERR = `E${RAND}`;
45
const COLL = `C${RAND}`;
0 ignored issues
show
Unused Code introduced by
The constant COLL seems to be never used. Consider removing it.
Loading history...
46
47
// ===========================================
48
// COMMON FUNCTIONS
49
// ===========================================
50
function onError (result, error) {
0 ignored issues
show
Unused Code introduced by
The parameter error is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
51
52
  console.log(result);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
53
54
}
55
56
function dlog (target) {
57
58
  if (isDebug) {
0 ignored issues
show
Bug introduced by
The variable isDebug seems to be never initialized.
Loading history...
59
60
    console.log(target);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
61
62
  }
63
64
}
65
66
function reconvert (str) {
67
68
  str = str.replace(/(\\u)(\w{1,4})/gi, function ($0) {
69
70
    return String.fromCharCode(parseInt(escape($0).replace(/(%5Cu)(\w{1,4})/g, '$2'), 16));
71
72
  });
73
  str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) {
74
75
    return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, '$2'), 16));
76
77
  });
78
  str = str.replace(/(&#)(\d{1,6});/gi, function ($0) {
79
80
    return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, '$2')));
81
82
  });
83
84
  return str;
85
86
}
87
88
function units (size) {
89
90
  return size > 1048576 ? `${0 | size / 1048576 }MB` :
91
    size > 1024 ? `${0 | size / 1024 }KB` :
92
      `${size }B`;
93
94
}
95
96
function fragment (div, a, b) {
97
98
  const frag = document.createDocumentFragment();
99
  frag.appendChild(document.createTextNode(a));
100
  if (b) {
101
102
    frag.appendChild(div.cloneNode());
103
    frag.appendChild(document.createTextNode(b));
104
105
  } else {
106
107
    frag.appendChild(document.createElement('br'));
108
109
  }
110
  return frag;
111
112
}
113
114
function change (node, query, name, set) {
115
116
  const list = node.querySelectorAll(query);
117
  let i = list.length;
118
  for (; i--;) {
119
120
    list[i].classList[set ? 'add' : 'remove'](name);
121
122
  }
123
124
}
125
126
function draw (str, current, isEmbed = false) {
127
128
  isJsonThisDocument = true;
0 ignored issues
show
Unused Code introduced by
The variable isJsonThisDocument seems to be never used. Consider removing it.
Loading history...
129
130
  const re = /("(?:((?:https?|file):\/\/(?:\\?\S)+?)|(?:\\?.)*?)")\s*(:?)|-?\d+\.?\d*(?:e[+-]?\d+)?|true|false|null|[[\]{},]|(\S[^-[\]{},"\d]*)/gi;
131
  let node = document.createElement('div');
132
  node.classList.add(DIV);
133
  const link = document.createElement('a');
134
  const span = document.createElement('span');
135
  const info = document.createElement('i');
136
  const colon = document.createTextNode(': ');
137
  const comma = fragment(node, ',');
138
  const path = [];
139
  const cache = {
140
    '{': fragment(node, '{', '}'),
141
    '[': fragment(node, '[', ']'),
142
  };
143
144
  node.className = `R${RAND}`;
145
  link.classList.add(`L${RAND}`);
146
  if (isEmbed) {
147
148
    info.classList.add(`IJSON${RAND}`);
149
150
  } else {
151
152
    info.classList.add(`I${RAND}`);
153
154
  }
155
156
  parse(str, re);
157
158
  current.innerHTML = node.innerHTML;
159
160
  function parse (str, re) {
161
162
    str = reconvert(str);
163
    let match; let val; let tmp; const i = 0;
0 ignored issues
show
Unused Code introduced by
The constant i seems to be never used. Consider removing it.
Loading history...
164
    const len = str.length;
165
    try {
166
167
      for (; match = re.exec(str);) {
168
169
        val = match[0];
170
        if (val == '{' || val == '[') {
171
172
          path.push(node);
0 ignored issues
show
Bug introduced by
The variable node is changed as part of the for loop for example by node.lastChild.previousSibling on line 174. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
173
          node.appendChild(cache[val].cloneNode(true));
174
          node = node.lastChild.previousSibling;
175
          node.len = 1;
176
          node.start = re.lastIndex;
177
178
        } else if ((val == '}' || val == ']') && node.len) {
179
180
          if (node.childNodes.length) {
181
182
            tmp = info.cloneNode();
183
            const content = node.len + (
184
              node.len == 1 ?
0 ignored issues
show
Best Practice introduced by
Comparing node.len to 1 using the == operator is not safe. Consider using === instead.
Loading history...
185
                val == ']' ? ' item, ' : ' property, ' :
186
                val == ']' ? ' items, ' : ' properties, '
187
            ) + units(re.lastIndex - node.start + 1);
188
189
            if (hideDetails) {
190
191
              tmp.setAttribute('title', content);
192
193
            } else {
194
195
              tmp.dataset.content = content;
196
197
            }
198
199
            if ((val = node.previousElementSibling) && val.className == KEY) {
200
201
              tmp.dataset.key = reconvert(val.textContent.slice(1, -1).replace(/'/, '\\\''));
202
203
            }
204
            node.parentNode.insertBefore(tmp, node);
205
206
          } else {
207
208
            node.parentNode.removeChild(node);
209
210
          }
211
          node = path.pop();
212
213
        } else if (val == ',') {
214
215
          node.len += 1;
216
          node.appendChild(comma.cloneNode(true));
217
218
        } else {
219
220
          tmp = span.cloneNode();
221
          tmp.textContent = match[1] || val;
222
          tmp.classList.add(match[3] ? KEY : match[1] ? STR : match[4] ? ERR : BOOL);
223
          node.appendChild(tmp);
224
          if (match[3]) {
225
226
            node.appendChild(colon.cloneNode());
227
228
          }
229
230
        }
231
232
      }
233
      document.title = '';
234
      JSON.parse(str);
235
236
    } catch (e) {
237
238
      dlog(e);
239
      // TODO: find a better way to report error
240
241
    }
242
243
  }
244
245
}
246